/**
 * Copyright (c) 2009-2011, chunquedong(YangJiandong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 
 * History:
 *     2010-05-05  Jed Young  Creation
 */
package chunmap.model.algorithm;

import chunmap.model.coord.Position;
import chunmap.model.elem.Envelope;
import chunmap.model.geom.GeoPoint;
import chunmap.model.geom.Geometry;
import chunmap.model.geom.GeometryCollection;
import chunmap.model.geom.GeometryException;
import chunmap.model.geom.LineString;
import chunmap.model.geom.Ring;
import chunmap.model.geom.Polygon;

public class EnvelopeAlgorithm {
	public static boolean hasIntersect(Envelope env,Geometry geom)
    {
        if (geom instanceof GeoPoint)
        {
        	Position p = ((GeoPoint)geom).getCoordinate();
            return env.contain(p);
        }
        else if (geom instanceof LineString)
        {
            LineString ls = (LineString)geom ;
            return env.toRing().hasIntersection(ls);
        }
        else if (geom instanceof Polygon)
        {
            Polygon pg = (Polygon)geom;
            Ring r = env.toRing();
            if (pg.getShell().containIn(env.getCenter()))
            {
                if (inHoles(r, pg))
                {
                    return false;
                }
                return true;
            }
            else
            {
                if (r.hasIntersection(pg.getShell())) return true;

                return false;
            }
        }
        else if (geom instanceof GeometryCollection)
        {
            GeometryCollection gs = (GeometryCollection)geom;
            for (Geometry g : gs)
            {
                if (hasIntersect(env, g)) return true;
            }
            return false;
        }
        else
        {
            throw new GeometryException();
        }
    }

    private static boolean inHoles(LineString ls, Polygon pg)
    {
        for (Ring r : pg.getHoles())
        {
            if (r.containLineStringIn(ls)) return true;
        }
        return false;
    }
}